<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 设备借用->可借用设备 </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <!--         <el-cascader :options='options' filterable v-model='op.options' class='handle-input mr10'></el-cascader>-->
        <el-input style="width: 250px" v-model="query.cgText" placeholder="输入关键字" class="handle-input mr10" clearable>
        </el-input>
        <el-button type="primary" icon="el-icon-search" style="margin-left: 8px" size="mini" @click="handleQuery">搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="primary" icon="el-icon-check" size="mini" @click="dialogVisib">借用</el-button>

      </div>

      <el-table v-loading="loading" ref="multipleTable" :data="canAbleList" class="table" border
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="100" align="center"></el-table-column>
        <el-table-column label="序号" type="index" align="center" width="50"> </el-table-column>
        <el-table-column label="设备名" prop="name" align="center"></el-table-column>
        <el-table-column label="设备类型   " prop="type" align="center"></el-table-column>
        <el-table-column label="设备描述" prop="remark" align="center"></el-table-column>
        <el-table-column label="所属实验室" prop="labname" :show-overflow-tooltip="true" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-message" @click="watchImage(scope.row)">查看照片 </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class='pagination' style='text-align: left;'>
        <el-pagination background layout="total,sizes,prev, pager, next,jumper" :current-page="pageInfo.currentPage"
          :page-size="pageInfo.pageSize" :total="pageInfo.pageTotal" :page-sizes="[5, 10, 20, 50]"
          @size-change="handleSizeChange" @current-change="handleCurrentChange">

        </el-pagination>
      </div>


      <!--                        @click="handleAdd"-->


    </div>
    <el-dialog title="选择预计归还时间" :visible.sync="dialogVisible " width="30%" :before-close="handleClose">
      <div class="block">
        <span class="demonstration">归还时间：</span>
        <el-date-picker v-model="value1" type="datetime" placeholder="选择日期时间" default-time="12:00:00">
        </el-date-picker>
      </div>


      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible  = false">取 消</el-button>
        <el-button type="primary" @click="updateBorrow">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 照片弹窗 -->
    <el-dialog title="设备照片" :visible.sync="dialogImage" width="30%" class="imageDialog">
      <el-image style="width: 100%; height: 300px" :src="url" :preview-src-list="srcList">
      </el-image>
      <span slot="footer">
        <el-button @click="dialogImage = false">取 消</el-button>
        <el-button type="primary" @click="dialogImage = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>

<script>
import { parseTime } from '../../utils/common';
import { getInfo } from '@/api/login';

import { listRole, getRole, delRole, addRole, updateRole, dataScope, changeRoleStatus } from "../../api/system/role";
import { treeselect as deptTreeselect, roleDeptTreeselect } from "../../api/system/dept";
import { treeselect as menuTreeselect, roleMenuTreeselect } from "../../api/system/menu";

import variable from '@/utils/request';

export default {
  name: "Role",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      srcList: [],
      url: "",
      dialogImage: false,
      tableData: [],
      //value2: new Date(2016, 9, 10, 12, 0o0),
      value2: '12:00',
      value1: '',
      startTime: (new Date()).Format('yyyy-MM-dd hh:mm:ss'),
      dialogVisible: false,
      pageInfo: {
        currentPage: 1,
        pageSize: 10,
        pageTotal: 80
      },

      options: [],
      options1: {
        taskStatus: [
          {
            label: '未借用',
            value: '0'
          },
          {
            label: '已借用',
            value: '1'
          },
          {
            label: '损坏',
            value: '2'
          },
          {
            label: '借出未归还',
            value: '3',
          }
        ]
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备表格数据
      canAbleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],
      // 数据范围选项
      dataScopeOptions: [
        {
          value: "1",
          label: "全部数据权限"
        },
        {
          value: "2",
          label: "自定数据权限"
        },
        {
          value: "3",
          label: "本部门数据权限"
        },
        {
          value: "4",
          label: "本部门及以下数据权限"
        },
        {
          value: "5",
          label: "仅本人数据权限"
        }
      ],
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleName: undefined,
        roleKey: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      query: {
        cgText: '',
        taskStatus: undefined
      },
      equip: {
        deptId: '',
        type: ''
      }
    };
  },
  created() {
    this.getAvailable();
  },
  methods: {
    //查看照片
    watchImage(row) {
      this.dialogImage = true;
      console.log(row);
      //假设照片路径字段为urlList['',';','']
      // this.url = row.urlList[0];
      // this.srcList.row.urlList;
      const url = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.jj20.com%2Fup%2Fallimg%2F1111%2F0R11Q22326%2F1PR1122326-6.jpg&refer=http%3A%2F%2Fpic.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1666430544&t=c093fab6dd4e5692f12628beb388aa2b"
      this.url = url;
      this.srcList.push(url);
    },
    dialogVisib() {
      if (this.ids.length != 0) {
        this.dialogVisible = true
      } else {
        this.$message({
          type: 'info',
          message: '请选择其中一行或多行'
        });
        this.dialogVisible = false
        this.getAvailable();

      }
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => { });
    },
    //设备列表
    getAvailable() {
      this.loading = true;
      let json = {
        keywords: this.query.cgText,
        pageSize: this.pageInfo.pageSize,
        pageNum: this.pageInfo.currentPage
      }
      variable.getaxiosPost('/equip/getAvailable', json).then((res) => {
        console.log(res);
        if (res.data) {
          this.pageInfo.pageTotal = res.data.total;
          this.canAbleList = res.data.list;
        }
        this.loading = false;
      });
    },
    //获取行id
    getSelectIds() {
      let rows = this.$refs.multipleTable.selection;
      let ids = [];
      rows.forEach((item) => {
        ids.push(item.id)
      })
      console.log(ids)
      return ids;
    },
    //借出
    updateBorrow() {
      this.loading = true;
      let ids = this.getSelectIds();
      // let data = {
      //   ids : JSON.stringify(ids),
      //   startTime :  JSON.stringify(this.startTime),
      //   endTime : JSON.stringify(this.value1 + this.value2),
      // }
      let data = {
        ids: JSON.stringify(ids),
        startTime: this.startTime,
        //this.tableData=JSON.parse(JSON.stringify(this.tableData));
        endTime: parseTime(this.value1, '{y}-{m}-{d} {h}:{i}:{s}'),
      }
      if (this.value1.length != 0) {
        if (ids.length != 0) {
          variable.getaxiosPost('/borrow/addBorrow', data).then((res) => {
            console.log(res);
            this.dialogVisible = false
            this.getAvailable();
            if (res.code == '0') {
              this.$message.success('借用成功', {
                duration: 2000
              });
              this.dialogVisible = false
              this.getAvailable();

            } else {
              this.$message.error(res.data.message, {
                duration: 2000,
              })
              this.dialogVisible = false
            }
            this.loading = false;
          });
        }
        else {
          this.$message({
            type: 'info',
            message: '请选择其中一行或多行'
          });
          this.dialogVisible = false
          this.getAvailable();

        }
      }
      else {
        this.$message({
          type: 'info',
          message: '请输入归还日期'
        });
        this.dialogVisible = false
        this.getAvailable();
      }
    },
    /**
     * 分页切换
     */
    handleCurrentChange(val) {
      console.log(val);
      this.pageInfo.currentPage = val;
      this.getAvailable();
    },
    /**
     * 分页大小切换
     */
    handleSizeChange(val) {
      this.pageInfo.pageSize = val;
      this.getAvailable();
    },
    /** 查询菜单树结构 */
    getMenuTreeselect() {
      menuTreeselect().then(response => {
        this.menuOptions = response.data;
      });
    },
    /** 查询部门树结构 */
    getDeptTreeselect() {
      deptTreeselect().then(response => {
        this.deptOptions = response.data;
      });
    },


    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    // 所有部门节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.dept.getCheckedKeys();
      // 半选中的部门节点
      let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    /** 根据角色ID查询菜单树结构 */
    getRoleMenuTreeselect(roleId) {
      return roleMenuTreeselect(roleId).then(response => {
        this.menuOptions = response.data.menus;
        return response;
      });
    },
    /** 根据角色ID查询部门树结构 */
    getRoleDeptTreeselect(roleId) {
      return roleDeptTreeselect(roleId).then(response => {
        this.deptOptions = response.depts;
        return response;
      });
    },
    // 角色状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$confirm('确认要"' + text + '""' + row.roleName + '"角色吗？').then(function () {
        return changeRoleStatus(row.roleId, row.status);
      }).then(() => {
        this.$message.success(text + "成功");
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.menuExpand = false,
        this.menuNodeAll = false,
        this.deptExpand = true,
        this.deptNodeAll = false,
        this.form = {
          roleId: undefined,
          roleName: undefined,
          roleKey: undefined,
          roleSort: 0,
          status: "0",
          menuIds: [],
          deptIds: [],
          menuCheckStrictly: true,
          deptCheckStrictly: true,
          remark: undefined
        };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getAvailable();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      Object.keys(this.query).forEach(key => { this.query[key] = '' })
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.roleId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleDataScope":
          this.handleDataScope(row);
          break;
        case "handleAuthUser":
          this.handleAuthUser(row);
          break;
        default:
          break;
      }
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      } else if (type == 'dept') {
        let treeList = this.deptOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
      } else if (type == 'dept') {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions : []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'menu') {
        this.form.menuCheckStrictly = value ? true : false;
      } else if (type == 'dept') {
        this.form.deptCheckStrictly = value ? true : false;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getMenuTreeselect();
      this.open = true;
      this.title = "选择时间";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const roleId = row.roleId || this.ids
      const roleMenu = this.getRoleMenuTreeselect(roleId);
      getRole(roleId).then(response => {
        this.form = response.data;
        this.open = true;
        console.log(this.form)
        this.$nextTick(() => {
          roleMenu.then(res => {
            let checkedKeys = res.data.checkedKeys
            checkedKeys.forEach((v) => {
              this.$nextTick(() => {
                this.$refs.menu.setChecked(v, true, false);
              })
            })
          });
        });
        this.title = "修改角色";
      });
    },
    /** 选择角色权限范围触发 */
    dataScopeSelectChange(value) {
      if (value !== '2') {
        this.$refs.dept.setCheckedKeys([]);
      }
    },
    /** 分配数据权限操作 */
    handleDataScope(row) {
      this.reset();
      const roleDeptTreeselect = this.getRoleDeptTreeselect(row.roleId);
      getRole(row.roleId).then(response => {
        this.form = response.data;
        this.openDataScope = true;
        this.$nextTick(() => {
          roleDeptTreeselect.then(res => {
            this.$refs.dept.setCheckedKeys(res.checkedKeys);
          });
        });
        this.title = "分配数据权限";
      });
    },
    /** 分配用户操作 */
    handleAuthUser: function (row) {
      const roleId = row.roleId;
      this.$router.push("/system/role-auth/user/" + roleId);
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.roleId != undefined) {
            this.form.menuIds = this.getMenuAllCheckedKeys();
            // this.form.menuIds = [];
            updateRole(this.form).then(response => {
              this.$message.success("修改成功");
              this.open = false;
              this.getAvailable();
            });
          } else {
            this.form.menuIds = this.getMenuAllCheckedKeys();
            addRole(this.form).then(response => {
              this.$message.success("新增成功");
              this.open = false;
              this.getAvailable();
            });
          }
        }
      });
    },
    /** 提交按钮（数据权限） */
    submitDataScope: function () {
      if (this.form.roleId != undefined) {
        this.form.deptIds = this.getDeptAllCheckedKeys();
        dataScope(this.form).then(response => {
          this.$message.success("修改成功");
          this.openDataScope = false;
          this.getAvailable();
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.roleId || this.ids;
      this.$confirm('是否确认删除角色编号为"' + roleIds + '"的数据项？').then(function () {
        return delRole(roleIds);
      }).then(() => {
        this.getAvailable();
        this.$message.success("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/role/export', {
        ...this.queryParams
      }, `role_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped lang="scss">
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

::v-deep .equip .el-form .el-form-item .el-form-item__label {
  width: 100px !important;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}

.imageDialog {
  ::v-deep .el-dialog__body {
    padding: 10px;
    padding-bottom: 0 !important;
  }
}
</style>
